package states

import (
	"go_server/game_server/api/service/bag"
	"go_server/game_server/api/service/build"
	"go_server/game_server/dao/count_down_dao"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/event_manager"
	"go_server/game_server/event_manager/event_data/event_impl"
	"go_server/game_server/initializer/map_data_init"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/game_server/world_manager"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
	"go_server/zinx/znet"
)

type WeedApi struct {
	znet.BaseRouter
}

// 除草
func (*WeedApi) Handle(request ziface.IRequest) {
	msg := &pb.WeedC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	config := config_manager.GettableMap3DConfigSheetSundriesById(msg.WeedId)
	if config.Reward == nil || config.ClickType != CLICK_TYPE1 {
		zlog.Errorf("铲除杂草配置奖励不存在")
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_WEED_CONFIG_UNFIND, nil)
		return
	}

	fields := []string{"had_weed_list"}
	row := count_down_dao.GetCountDownByRoleId(roleId, fields)

	hadWeedList := make([]int32, 0)
	if row != nil && row.HadWeedList != nil {
		hadWeedList = row.HadWeedList
	}

	if len(hadWeedList) > 0 {
		eventSet := util.NewSet[int32]()
		eventSet.AddValue(hadWeedList)
		if eventSet.Contains(msg.WeedId) {
			zlog.Errorf("当前杂草已被铲除")
			world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_WEED_HAD_GOT, nil)
			return
		}
	}

	if len(config.Condition) > 0 {
		for _, con := range config.Condition {
			if build.GetMaxLevelByBuildType(roleId, con.Value[0]) >= con.Value[1] {
				continue
			}
			world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_WEED_CONDITION_ERR,
				[]string{string(con.Value[0]), string(con.Value[1])})
			return
		}
	}

	hadWeedList = append(hadWeedList, msg.WeedId)

	res := &pb.WeedS2C{
		HadWeedList: hadWeedList,
	}

	// 优先返回下行
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_Weed), res)

	if config.UnlockFogs > 0 {
		build.UnlockRoleMapBlock(conn, roleId, map_data_init.InitMapID, config.UnlockFogs, false)
	}

	defer func() {
		countDown := count_down_dao.CountDown{
			RoleId:      roleId,
			HadWeedList: hadWeedList,
		}
		count_down_dao.UpdateCountDown(&countDown, fields)
	}()

	// 发送奖励
	bag.AddItemArrayInt32(roleId, config.Reward)

	// 创建清除杂物事件
	event_manager.EventManagerObj.FireEventData(event_impl.NewCleanUpDebrisEvent(conn, map[string]int32{
		"id":    msg.WeedId, // 清除的杂草id
		"value": 1,          // 次数
	}))
}
